package com.fengye.school.service;

import com.fengye.school.model.school.Student;
import com.fengye.school.response.ResponsePageResult;
import com.fengye.school.respository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class StudentService {

    @Resource
    private StudentRepository studentRepository;

    @Transactional
    public Student save(Student student){
        Student save = studentRepository.save(student);
        log.info("保存成功, student={}", save);
        return save;
    }

    public List<Student> list() {
        return studentRepository.findAll();
    }

    public ResponsePageResult<Student> listByPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        Page<Student> all = studentRepository.findAll(pageable);
        return ResponsePageResult.success("获取学生分页数据成功", all.getTotalElements(), all.getContent());
    }

    public void deleteAll(Long[] ids) {
        Arrays.stream(ids).forEach(id -> studentRepository.deleteById(id));
    }

    public void deleteById(Long id) {
        studentRepository.deleteById(id);
    }
}
